/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-15 19:20:57
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-15 19:25:22
 * @FilePath: \react_nest_demo\react_vite\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { message } from 'antd';

interface IBase<T = string | null> {
  data: T;
  code: number;
  msg: string;
}

export const BASE_URL = 'http://localhost:3000';

const request = axios.create({ 
  baseURL: `${BASE_URL}`
});

export const handleErrorType = (error: Error) => {
  return error as AxiosError<IBase>;
}

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 获取token
    const token = JSON.parse(localStorage.getItem("token") as string)?.data;

    if (token) {
      config.headers.Authorization = token;
    }

    return config;
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => {
    const data = response?.data as IBase;

    if (data.code === 0 && data.msg !== undefined) message.success(data.msg);

    return response;
  },
  error => {
    const { response } = handleErrorType(error) || {};
    message.warning(response?.data?.msg ?? "出现未知的错误，请重试");
  }
);

export default async function makeRequest<T>(
  url: string,
  options?: AxiosRequestConfig
) {
  return (
    await request({
      url,
      ...options,
    })
  ).data as IBase<T>;
}